package common

import (
	"database/sql"
	"encoding/json"
	"gitee.com/go_library/common/log"
	"github.com/go-redis/redis/v7"
	"github.com/jmoiron/sqlx"
)

/**
 * 设定数据存储方式
 */
type DbConfig struct {
	UserName string `yaml:"username"`
	Password string `yaml:"password"`
	IP       string `yaml:"ip"`
	Port     string `yaml:"port"`
	Database string `yaml:"database"`
}

type RedisConfig struct {
	Port string `yaml:"port"`
	IP   string `yaml:"ip"`
}

// 封装SQLx,用来记录日志
type DB struct {
	sqlx.DB
}

func (db *DB) Query(query string, args ...interface{}) (*sql.Rows, error) {
	log.Db.Println(query, args)
	return db.DB.Query(query, args...)
}

func (db *DB) QueryRow(query string, args ...interface{}) *sql.Row {
	log.Db.Println(query, args)
	return db.DB.QueryRow(query, args...)
}

func (db *DB) Exec(query string, args ...interface{}) (sql.Result, error) {
	log.Db.Println(query, args)
	return db.DB.Exec(query, args...)
}

func (db *DB) NamedExec(query string, arg interface{}) (sql.Result, error) {
	_json, _ := json.Marshal(arg)
	log.Db.Println(query, string(_json))
	return db.DB.NamedExec(query, arg)
}

func (db *DB) Get(dest interface{}, query string, args ...interface{}) error {
	log.Db.Println(query, args)
	return db.DB.Get(dest, query, args...)
}

func (db *DB) Select(dest interface{}, query string, args ...interface{}) error {
	log.Db.Println(query, args)
	return db.DB.Select(dest, query, args...)
}

var Sql *DB
var Redis *redis.Client

func InitStorage() (err error) {
	config := Config.Db
	dsn := config.UserName + ":" + config.Password + "@(" + config.IP + ":" + config.Port + ")/" + config.Database
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		return err
	}
	Sql = &DB{
		*sqlx.NewDb(db, "default"),
	}

	Redis = redis.NewClient(&redis.Options{
		Addr: Config.Redis.IP + ":" + Config.Redis.Port,
	})
	if _, err = Redis.Ping().Result(); err != nil {
		return err
	}
	return
}
